package cn.dankal.flyaudio.personal.notificaiton

import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import cn.dankal.basiclib.DankalApplication
import cn.dankal.basiclib.GlideApp
import cn.dankal.basiclib.base.activity.BaseStateActivity
import cn.dankal.basiclib.base.mullist.adapter.MultipleAdapter
import cn.dankal.basiclib.base.mullist.adapter.Rule
import cn.dankal.basiclib.base.mullist.adapter.State
import cn.dankal.basiclib.base.mullist.holder.SuperHolder
import cn.dankal.basiclib.base.mullist.listener.OnSelectListener
import cn.dankal.basiclib.protocol.MainProtocol.*
import cn.dankal.basiclib.util.DisplayHelper.dp2px
import cn.dankal.basiclib.util.ToastUtils
import cn.dankal.basiclib.util.image.PicUtils
import cn.dankal.basiclib.widget.CommonDialog
import cn.dankal.basiclib.widget.titlebar.TitleWithAction
import cn.dankal.business.pojo.NotificationBean
import cn.dankal.business.Constants
import cn.dankal.flyaudio.R
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.request.target.BitmapImageViewTarget
import kotlinx.android.synthetic.main.activity_notification_list.*


open class NotificationListActivity : BaseStateActivity(), NotifyContract.View {
    override fun delete(message: String?) {
    }

    lateinit var list: MutableList<NotificationBean>
    var equalsEdit = true
    var notificationAdapter = MultipleAdapter<NotificationBean>()
    lateinit var tv_action: TextView
    var type: Int? = null
    lateinit var notifyPresenter: NotifyPresenter
    /**
     * uuid列表
     */
    var uuids = mutableListOf<NotificationBean>()
    /**
     * 显示删除按钮
     */
    lateinit var commonDialog: CommonDialog

    var isRefresh: Boolean = false


    override fun contentView(): Any {
        return swipe_toload_layout
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_notification_list
    }

    override fun initComponents() {
        type = intent.getIntExtra(Constants.TYPE, 0)
        var titleWithAction = TitleWithAction(
                when (type) {
                    Constants.MSG_TYPE_SYSTEM -> {
                        "系统消息"
                    }
                    Constants.MSG_TYPE_APPOINT -> {
                        "预约消息"
                    }
                    else -> {
                        "评论消息"
                    }
                })

        addTitleBar(titleWithAction)

        tv_action = findViewById(R.id.tv_action)
        tv_action.setCompoundDrawables(null, null, null, null)

        tv_action.setOnClickListener {
            equalsEdit = tv_action.text.equals("编辑")
            ll_del.visibility = if (equalsEdit) View.VISIBLE else View.GONE
            notificationAdapter.setOpenSelect(equalsEdit, 100)

            if (!equalsEdit) {
                var drawable = resources.getDrawable(R.mipmap.pic_mine_circle)
                drawable.setBounds(0, 0, dp2px(this, 19), dp2px(this, 19))
                tv_select_all.setCompoundDrawables(drawable, null, null, null)
            }
            notificationAdapter.unSelectAll()

            tv_action.text = if (equalsEdit) "完成" else "编辑"
        }

        tv_action.text = "编辑"

        tv_select_all.setOnClickListener {
            selectAll()
        }
        swipe_target.adapter = notificationAdapter
        swipe_target.layoutManager = LinearLayoutManager(this)
        /* (swipe_target as DeleteRecyclerView).setDelOnItemClickListener(object : OnDelItemClickListener {
             override fun onItemClick(view: View?, position: Int) {
                 ToastUtils.showShort("点击")
                 TODO("评论消息，预约消息，系统消息")
             }
             override fun onDeleteClick(position: Int) {
                 ToastUtils.showShort("删除")
             }
         })*/
        swipe_toload_layout.setOnRefreshListener {
            isRefresh = false
            notifyPresenter.requestData(isRefresh)
        }

        swipe_toload_layout.setOnLoadMoreListener {
            isRefresh = true
            notifyPresenter.requestData(isRefresh)
        }
        swipe_target.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
        chooseSetting()

        tv_del.setOnClickListener {
            showComfirmDialog()
        }
        tv_read.setOnClickListener {
            showRedMessageDialog()
        }
        notifyPresenter = NotifyPresenter(type)
        notifyPresenter.attachView(this)

        showLoading()
    }

    override fun onUpdateRemind() {
        swipe_toload_layout.isLoadingMore = false
        swipe_toload_layout.isRefreshing = false
        list.removeAll(uuids)
        notificationAdapter.uploadData(list)
        notificationAdapter.notifyDataSetChanged()
    }


    /**
     * 多选和删除的配置
     */
    private fun chooseSetting() {
        notificationAdapter.setOnSelectListener(object : OnSelectListener<NotificationBean> {
            override fun onSelectChange(t: NotificationBean?, position: Int, isSelect: Boolean) {
                t?.apply {
                    if (isSelect) {
                        uuids.add(this)
                    } else {
                        uuids.remove(this)
                        equalsEdit = true
                        var drawable = resources.getDrawable(R.mipmap.pic_mine_circle)
                        drawable.setBounds(0, 0, dp2px(this@NotificationListActivity, 19), dp2px(this@NotificationListActivity, 19))
                        tv_select_all.setCompoundDrawables(drawable, null, null, null)
                    }
                }
            }

            override fun onSelectFailure() {}

            override fun onSelectComplete() {}
        })

        if (type == Constants.MSG_TYPE_COMMENT) {//评论消息
            notificationAdapter.addRule(object : Rule<NotificationBean>(R.layout.rv_item_notification_tow) {
                override fun doBindData(`object`: Any?): Boolean {
                    return true
                }

                override fun onDataBind(holder: SuperHolder, t: NotificationBean, state: State<*>?, position: Int) {

                    holder.setText(R.id.tv_item_name, t.receiveName)
                    holder.setText(R.id.tv_item_content, t.content)
                    holder.setText(R.id.tv_item_time, t.createTime)

                    var ivHead: ImageView = holder.getView(R.id.iv_user)

                    GlideApp.with(DankalApplication.getContext()).asBitmap().centerCrop().error(R.mipmap.pic_ill_4).load(PicUtils.getUrl(t.receiveAvatar)).into(object : BitmapImageViewTarget(ivHead) {
                        override fun setResource(resource: Bitmap?) {
                            val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource)
                            circularBitmapDrawable.isCircular = true
                            ivHead.setImageDrawable(circularBitmapDrawable)
                        }
                    })

                    holder.setOnClickListener(R.id.item_layout) {
                        ARouter.getInstance().build(CURRENT_DETAIL)
                                .withString(Constants.UUID, t.userInfoUuid)
                                .withString("uuid_tow", t.uuid)
                                .navigation()
                    }

                    var ivSelect = holder.itemView?.findViewById<ImageView>(R.id.iv_select)
                    if (!notificationAdapter.isOpenSelect) {
                        ivSelect?.visibility = View.GONE
                        return
                    }
                    ivSelect?.visibility = View.VISIBLE
                    ivSelect?.isSelected = (state?.state == State.STATE_SELECTED)
                    ivSelect?.setOnClickListener {
                        notificationAdapter.toggle(position)
                        ivSelect?.isSelected = !ivSelect?.isSelected
                    }
                }
            })
        } else {
            notificationAdapter.addRule(object : Rule<NotificationBean>(R.layout.rv_item_notification) {
                override fun doBindData(`object`: Any?): Boolean {
                    return true
                }

                override fun onDataBind(holder: SuperHolder, t: NotificationBean, state: State<*>?, position: Int) {

                    when (type) {
                        Constants.MSG_TYPE_SYSTEM -> {
                            holder.setText(R.id.tv_system_message, t.title)
                            holder.setText(R.id.tv_time, t.createTime)
                            holder.setVisibility(R.id.tv_system_tips, View.GONE)
                        }
                        Constants.MSG_TYPE_COMMENT -> {//评论消息title为null
                            holder.setText(R.id.tv_system_message, t.content)
                            holder.setText(R.id.tv_time, t.createTime)
                            holder.setVisibility(R.id.tv_system_tips, View.GONE)
                        }
                        else -> {
                            holder.setText(R.id.tv_system_message, t.title)
                            holder.setText(R.id.tv_time, t.createTime)
                            holder.setVisibility(R.id.tv_system_tips, View.VISIBLE)
                            holder.setText(R.id.tv_system_tips, t.content)
                        }
                    }

                    holder.setOnClickListener(R.id.item_layout) {
                        //notifyPresenter.update_remind(t, false)
                        when (type) {
                            Constants.MSG_TYPE_SYSTEM -> {
                                val linkCss = "<style type=\"text/css\"> " +
                                        "html,body {padding:0;margin:0;}" +
                                        "img {" +
                                        "width:100%;" +
                                        "height:auto;" +
                                        "}" +
                                        "</style>"

                                val html = "<html><header>$linkCss</header>${t.content}</body></html>"

                                ARouter.getInstance().build(NORMAL_WEBVIEW)
                                        .withString("title", "系統消息")
                                        .withString("url", html)
                                        .withString("uuid", t.uuid)
                                        .navigation()
                            }
                            //活动消息
                            Constants.MSG_TYPE_APPOINT -> {
                                ARouter.getInstance().build(ACTIVITY_DETAIL)
                                        .withString(Constants.UUID, t.userApplyUuid)
                                        .withString("UUID_TOW", t.uuid)
                                        .withString(Constants.INTO_TYPE, "2")
                                        .navigation()
                            }
                            else -> {
                                //评论消息
                                ARouter.getInstance().build(CURRENT_DETAIL)
                                        .withString(Constants.UUID, t.userInfoUuid)
                                        .withString("uuid_tow", t.uuid)
                                        .navigation()
                            }
                        }
                    }

                    var ivSelect = holder.itemView?.findViewById<ImageView>(R.id.iv_select)
                    if (!notificationAdapter.isOpenSelect) {
                        ivSelect?.visibility = View.GONE
                        return
                    }
                    ivSelect?.visibility = View.VISIBLE
                    ivSelect?.isSelected = (state?.state == State.STATE_SELECTED)
                    ivSelect?.setOnClickListener {
                        notificationAdapter.toggle(position)
                        ivSelect?.isSelected = !ivSelect?.isSelected
                    }
                }
            })
        }


    }

    override fun obtainData() {
        notifyPresenter.requestData(false)
    }

    override fun render(t: MutableList<NotificationBean>?) {
        showContent()
        swipe_toload_layout.isRefreshing = false
        swipe_toload_layout.isLoadingMore = false

        if (!isRefresh) {
            if (t == null || t.isEmpty()) {
                showEmpty()
                tv_action.visibility = View.GONE
                showToast("暂无数据")
            } else {
                this.list = t
            }
        } else {
            if (t == null || t.isEmpty()) {
                showToast("没有更多啦")
            } else {
                this.list.addAll(t)
            }
        }
        try {
            list?.let {
                notificationAdapter.uploadData(list)
                notificationAdapter.notifyDataSetChanged()
            }
        } catch (e: Exception) {
        }

    }


    private fun showComfirmDialog() {
        // 如果有选中的消息就进行操作
        if (uuids != null && uuids.size > 0) {

            val builder = CommonDialog.Builder(this)
            builder.setTitle("是否确认删除该信息？")

            builder.setNegativeButton("取消",
                    resources.getColor(R.color.color14)) {
                commonDialog.dismiss()

            }

            builder.setPositiveButton("删除",
                    resources.getColor(R.color.colorPrimary)) {
                notifyPresenter.update_remind(uuids, true)
                commonDialog.dismiss()
            }
            commonDialog = builder.create()
            commonDialog.show()
        } else {
            ToastUtils.showShort("暂无操作项")
        }
    }

    private fun showRedMessageDialog() {
        // 如果有选中的消息就进行操作
        if (uuids != null && uuids.size > 0) {

            val builder = CommonDialog.Builder(this)

            if (uuids.size < list.size) {
                builder.setTitle("是否要将所选标记为已读？")
            } else {
                builder.setTitle("是否要全部标记为已读？")
            }

            builder.setNegativeButton("取消",
                    resources.getColor(R.color.color14)) {
                commonDialog.dismiss()

            }

            builder.setPositiveButton("确定",
                    resources.getColor(R.color.colorPrimary)) {
                notifyPresenter.update_read(uuids, false)
                commonDialog.dismiss()
            }
            commonDialog = builder.create()
            commonDialog.show()
        } else {
            ToastUtils.showShort("暂无操作项")
        }
    }

    private fun selectAll() {
        var drawable: Drawable
        if (equalsEdit) {
            drawable = resources.getDrawable(R.mipmap.pic_mine_circle_light)
            equalsEdit = false
            notificationAdapter.selectAll()
        } else {
            drawable = resources.getDrawable(R.mipmap.pic_mine_circle)
            equalsEdit = true
            notificationAdapter.unSelectAll()
        }
        drawable.setBounds(0, 0, dp2px(this, 19), dp2px(this, 19))
        tv_select_all.setCompoundDrawables(drawable, null, null, null)

        notificationAdapter.maxSelectCount = 100

    }

    /**
     * 消息读取完的回调
     */
    override fun onRead() {
        notifyPresenter.requestData(false)
        equalsEdit = tv_action.text.equals("编辑")
        ll_del.visibility = if (equalsEdit) View.VISIBLE else View.GONE
        notificationAdapter.setOpenSelect(equalsEdit, 100)

        if (!equalsEdit) {
            var drawable = resources.getDrawable(R.mipmap.pic_mine_circle)
            drawable.setBounds(0, 0, dp2px(this, 19), dp2px(this, 19))
            tv_select_all.setCompoundDrawables(drawable, null, null, null)
        }
        notificationAdapter.unSelectAll()

        tv_action.text = if (equalsEdit) "完成" else "编辑"
    }
}

